﻿using System;
using System.Configuration;
using System.Runtime.Remoting;
using MongoDB.Driver;

namespace Yamfinder.Data
{
    public class DataSource : IDataSource
    {
        private readonly MongoServer _server;
        private readonly MongoDatabase _yamfinderDatabase;

        public DataSource()
        {
            var connectionString = ConfigurationManager.AppSettings["MongoConnectionString"];

            if (string.IsNullOrEmpty(connectionString))
                throw new ServerException("'MongoConnectionString' AppSetting in the Web.config is blank or does not exist. Please enter a value and restart the service.");

            _server = MongoServer.Create(connectionString);

            var databaseName = ConfigurationManager.AppSettings["MongoDatabaseName"];

            if (string.IsNullOrEmpty(connectionString))
                throw new ServerException("'MongoDatabaseName' AppSetting in the Web.config is blank or does not exist. Please enter a value and restart the service.");

            _yamfinderDatabase = _server.GetDatabase(databaseName);
        }

        public MongoCollection<T> GetCollection<T>(string collectionName)
        {
            return _yamfinderDatabase.GetCollection<T>(collectionName);
        }

        public MongoCollection GetRawCollection(string collectionName)
        {
            return _yamfinderDatabase.GetCollection(collectionName);
        }
    }
}